﻿using AppDataStruct;
using ComLib.ComType;
using ComUIControl;
using EECMISWS;
using KWindow.KPageCore;
using LogLib;
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YSLPages
{
    public partial class PageUploading : PageControlBase
    {
     
        private PreApplyInfo _appInfo = null;

        private SFZInfo _sfz = new SFZInfo();

        private bool _uploadResult = false;

        private PictureBox pictureBox1 = null;

        private Image imgUploading = null;

        private Image imgUploadFailed = null;

        private Label labelTip = null;

        private WebDataAccess _webAccess = null;

        private string _personDataFile = "";

        private bool HZChecked = false;

        private bool SCZChecked = false;

        private bool DLZChecked = false;

        public PageUploading()
        {
            InitializeComponent();
            SetProcessBase(ProcessUploading.Instance);
        }

        private void GetControls()
        {
            labelTip = GetControl<Label>("labelTip") as Label;
            pictureBox1 = GetControl<PictureBox>("pictureBox1") as PictureBox;
            imgUploading = GetImage("Uploading");
            imgUploadFailed = GetImage("UploadFailed");
           
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            base.InitCtrls();
            GetControls();          
        }

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            pictureBox1.Image = imgUploading;
            _webAccess = WebDataAccess.Instance;
            _appInfo = Process.GetValue<PreApplyInfo>("PreApplyInfo");
            _uploadResult = false;
            _sfz = Process.GetValue<SFZInfo>("SFZInfo");
            if (Process.ContainsKey("HZChecked"))
            {
                HZChecked = Process.GetValue<bool>("HZChecked");
            }
            else
            {
                HZChecked = false;
            }
            if (Process.ContainsKey("DLZChecked"))
            {
                DLZChecked = Process.GetValue<bool>("DLZChecked");
            }
            else
            {
                DLZChecked = false;
            }
            if (Process.ContainsKey("SCZChecked"))
            {
                SCZChecked = Process.GetValue<bool>("SCZChecked");
            }
            else
            {
                SCZChecked = false;
            }
            string personDir = Process.GetValue<string>("PersonDataDirectory");
            if(_sfz != null)
            {
                _personDataFile = string.Format("{0}\\{1}.xml", personDir, _sfz.SFZH);
            }          
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            Process.SetValue("PreApplyInfo", _appInfo);
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            _uploadResult = false;
            _appInfo = null;
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {
            base.Close();
        }

        public override void StartWork()
        {
            base.StartWork();
            if (IsMainPage)
            {
                if (_appInfo == null || _sfz == null)
                {
                    Log.WriteAsync("没有有效的申请信息，直接进入下一步");
                    ClearData();
                    StopCountdown();
                    Process.ToNext();
                    return;
                }
                if (!_webAccess.Enabled)
                {
                    MessageBox.Show("全国版接口未启用.");
                    StopCountdown();
                    ClearData();
                    Process.ToNext();
                    return;
                }
                Speak("正在保存申请信息，请稍候");
                Task.Factory.StartNew(() =>
                {
                    _appInfo.SaveAsXml(_personDataFile);
                    if (!InitWebAccess())
                    {
                        string error = $"全国系统登录失败，请检查探针程序是否启动.\n{_webAccess.ErrorMessage}";
                        OnLoginFailed(error);
                        StopCountdown();
                        return;
                    }

                    if (UserAction == UserApplyAction.OnlyWeiYinTB
                    || UserAction == UserApplyAction.TakePhotoAndWeiYinTB)
                    {
                        if (SaveBioIdent())
                        {
                            OnUploadCompleted();
                        }
                        else
                        {
                            OnUploadFailed(_webAccess.ErrorMessage);
                        }
                    }
                    else if (UserAction == UserApplyAction.OnlyYSL
                    || UserAction == UserApplyAction.TakePhotoAndYSL)
                    {
                        if (SavePreApplyInfo())
                        {
                            OnUploadCompleted();
                        }
                        else
                        {
                            OnUploadFailed(_webAccess.ErrorMessage);
                        }
                    }
                });
            }            
        }

        private void OnLoginFailed(string error)
        {
            if(this.InvokeRequired)
            {
                Action<string> handler = new Action<string>(OnLoginFailed);
                this.Invoke(handler, new object[] { error });
                return;
            }
            Log.WriteAsync(error);
            MsgBox.Show(error);
            ClearData();
            Log.WriteAsync("上传失败，返回主页.");
            Process.ToHomeApp();
        }

        public override void StopWork()
        {
            base.StopWork();
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            Log.WriteAsync("倒计时结束，返回主页.");
            ClearData();
            Process.ToHome();
        }

        private bool InitWebAccess()
        {
            if (!_webAccess.Inited)
            {
                if (!_webAccess.Login())
                {
                    return false;
                }
            }
            return true;
        }

        private bool GetYWBH()
        {
            if (HZChecked && string.IsNullOrEmpty(_appInfo.HZSQ.YWBH))  //如果采集指纹，在这之前就获取过业务编号了
            {
                string ywbh_hz = _webAccess.MakeYWBH();
                if (string.IsNullOrEmpty(ywbh_hz))
                {
                    return false;
                }
                else
                {
                    _appInfo.HZSQ.YWBH = ywbh_hz;
                    Log.WriteAsync("护照申请业务编号获取成功:" + ywbh_hz);
                }
            }
            if (SCZChecked && string.IsNullOrEmpty(_appInfo.SCZSQ.YWBH))
            {
                string ywbh_scz = _webAccess.MakeYWBH();
                if (string.IsNullOrEmpty(ywbh_scz))
                {
                    return false;
                }
                else
                {
                    _appInfo.SCZSQ.YWBH = ywbh_scz;
                    Log.WriteAsync("港澳证申请业务编号获取成功:" + ywbh_scz);
                }
            }
            if (DLZChecked && string.IsNullOrEmpty(_appInfo.DLZSQ.YWBH))
            {
                string ywbh_dlz = _webAccess.MakeYWBH();
                if (string.IsNullOrEmpty(ywbh_dlz))
                {
                    return false;
                }
                else
                {
                    _appInfo.DLZSQ.YWBH = ywbh_dlz;
                    Log.WriteAsync("大陆证申请业务编号获取成功:" + ywbh_dlz);
                }
            }
            return true;
        }
      
        private bool SaveBioIdent()
        {
            if(HZChecked && File.Exists(_appInfo.SXQM_ZIP))
            {
                if (_webAccess.UploadSXQM)
                {
                    if (!_webAccess.SaveHandWriting(_appInfo))
                    {
                        Log.WriteAsync("手写签名保存失败:" + _webAccess.ErrorMessage);
                        return false;
                    }
                    Log.WriteAsync("手写签名保存成功!");
                }
                else
                {
                    Log.WriteAsync("设置不上传手写签名!");
                }
            }

            //if (UserAction == UserApplyAction.TakePhotoAndYSL
            //    || UserAction == UserApplyAction.TakePhotoAndWeiYinTB) 
            //{
                if (File.Exists(_appInfo.XCRX))
                {
                    if (!_webAccess.SaveLiveportrait(_appInfo))
                    {
                        Log.WriteAsync("现场人像保存失败:" + _webAccess.ErrorMessage);
                        return false;
                    }
                    else
                    {
                        Log.WriteAsync("现场人像保存成功!");
                    }
                }

            if (File.Exists(_appInfo.HightCapturePdf))
            {
                if (!_webAccess.SaveSFZHKBPdf(_appInfo))
                {
                    Log.WriteAsync("电子档案保存失败:" + _webAccess.ErrorMessage);
                    return false;
                }
                else
                {
                    Log.WriteAsync("电子档案保存成功!");
                }
            }
            //}

            if (!_webAccess.SaveFingerPrint(_appInfo))
            {
                Log.WriteAsync("指纹保存失败:" + _webAccess.ErrorMessage);
                return false;
            }
            else
            {
                Log.WriteAsync("指纹保存成功!");
            }

            return true;
        }

        private bool SavePreApplyInfo()
        {
            if (GetYWBH())
            {
                if (_webAccess.SavePreApply(_appInfo))
                {
                    if (SaveBioIdent())
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private void OnUploadCompleted()
        {
            _uploadResult = true;
            StopCountdown();
            Log.WriteAsync("预约申请信息入库成功!");
            Action handler = () =>
            {
                UpdateData();
                ClearData();
                if (Process.IsRunning)
                {
                    Process.ToNext();
                }
            };
            this.Invoke(handler);
        }

        private void OnUploadFailed(string error)
        {
            string msg = string.Format("申请信息入库失败: \n{0}", error);
            Log.WriteAsync(msg);
            if (!Process.IsRunning)
            {
                return;
            }          
            Action<string> handler = (e) =>
            {
                pictureBox1.Image = imgUploadFailed;
                SetTips(msg);
                CountdownSecond = 10;
                StartCountdown();
            };
            this.Invoke(handler, msg);
        }

        private void SetTips(string content)
        {
            labelTip.Text = content;
            int w = labelTip.Width;
            int x = (this.Width - w) / 2;
            labelTip.Left = x;
        }
    }
}
